<%@page language="java" contentType="text/html; charset=UTF-8" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="html" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<html:header title="新增借出单">

    <link rel="stylesheet" href="${baseUrl}css/public.css" media="all">

    <style type="text/css">
        .layui-table-cell {
            height:auto;
            text-overflow:inherit;
            white-space:normal;
            overflow: visible !important;
        }
    </style>

    <script>
        let option = {
            elem: '#selectHouse'
            ,placeholder:"${placeholder}"
            ,width:160
            , value: "0"
            ,clear:true
            , getChildren: function (value, callback) {
                var data = [];
                //表示是门店
                if (value == "0"){
                    get("${baseUrl}organization/store/getStores.action", function (res) {
                        if (res.code == 1){
                            data = res.data;
                            for (var i in data) {
                                data[i].value = data[i].id;
                                data[i].label = data[i].name;
                                delete data[i].id;
                                delete data[i].name;
                                data[i].hasChild = true;
                            }
                            callback(data);
                        }
                    });
                } else {
                    //表示是仓库
                    get("${baseUrl}organization/house/getHouseByStore.action?storeId="+value, function (res) {
                        if (res.code == 1){
                            if ("${type}" == "1") {
                                data.push({value:"", label:"全部"});
                            }
                            $.each(res.data, function (i,d) {
                                data.push({value:d.id, label:d.name, disabled:isTrue(d.locking)});
                            });

                            callback(data);
                        }
                    });
                }
            }
        };

        jQuery(function () {
            fixTableOperatorButton();
            $(window).focus();
            window.addEventListener("keydown", function(e) {
                if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
                    $("[lay-filter='save']").click();
                    e.preventDefault();
                }
            }, false);

            getByType("${baseUrl}",ORDER_TYPE.PD.type, $("[name='no']"));


            ajaxSelect("${baseUrl}user/user/getAll.action","userId");
            $("[name='date']").val(GMTToDate(new Date()));
            $("#cancel").click(function () {
                closeSubIframe();
            });

            $(".save").click(function (e) {
                $("[lay-filter='save']").click();
                e.preventDefault();
            });

            $(".select-goods").click(function () {
                let houseId = $("[name='houseId']").val();
                if (houseId == ""){
                    errTip("请选盘点仓库");
                    return;
                }
                let url = "${baseUrl}select/selectGoodsForCheckHouse.action?houseId="+houseId;
                openBigHtmlDialog("选择商品", url);
            });
        });


        layui.use(['form', 'table', 'laydate','ajaxCascader'], function () {
            let $ = layui.jquery,
                form = layui.form,
                table = layui.table,
                laydate = layui.laydate,
                cascader = layui.ajaxCascader;
            util = layui.util;

            laydate.render({
                elem: '#date'
            });
            laydate.render({
                elem: '#backDate'
            });

            renderTable([]);

            get("${baseUrl}organization/house/getDefault.action", function (res) {
                if (res.code == 1 && res.data.locking){
                    let chooseData = [];
                    chooseData.push(res.data.storeId);
                    chooseData.push(res.data.id);
                    option.chooseData = chooseData;

                    // Ajax传参模式
                    cascader.load(option);
                    $("[name='houseId']").val(res.data.id);
                }
            });
            // Ajax传参模式
            cascader.load(option);

            // 选择器点击事件的监听
            cascader.on('click', '#selectHouse', function(data){
                if (!data.disabled) {
                    errTip("该仓库暂未锁定，锁定后才可以进行盘点");
                    $(".cascader-clear").click();
                    $("[name='houseId']").val("");
                    renderTable([]);
                    return;
                }

                if ($("[name='houseId']").val() != data.value) {
                    //仓库改变之后要清空商品
                    renderTable([]);
                }

                $("[name='houseId']").val(data.value);
            });



            // 监听修改update到表格中
            form.on('select(unitSelect)', function (data) {
                let index = $(data.elem).parents('tr').data('index');
                let tableData = layui.table.cache.table;
                let goodsUnitVo = genUnitVo(tableData[index].goodsUnitVoList, data.value);

                tableData[index].unitId = data.value;
                tableData[index].times = goodsUnitVo.times;
                processAmount($(data.elem));
                processTotalRow();
            });

            form.verify({
                userId: function(value, item){ //value：表单的值、item：表单的DOM对象
                    if(value == null || value==""){
                        return '经办人不能为空';
                    }
                },
                date: function(value, item){ //value：表单的值、item：表单的DOM对象
                    if(value == null || value==""){
                        return '业务日期不能为空';
                    }
                }
            });


            form.on('submit(save)',function (data) {
                if (table.cache.table.length == 0) {
                    errTip("未选择任何商品");
                    return false;
                }
                if (data.field.houseId == ""){
                    errTip("盘点仓库不能为空");
                    return false;
                }


                let entity = data.field;
                delete entity.number;
                delete entity.unitId;
                entity.date = genDate(entity.date);

                //库存盘点单商品
                let list = new Array();
                $.each(table.cache.table,function (i,d) {
                    let vo = {};
                    vo.goodsId = d.goodsId;
                    vo.stockNum = d.stockNum;
                    vo.number = d.number;
                    if (d.sn) {
                        if (d.addGoodsSnList == undefined) {
                            vo.addNumber=0;
                            vo.delNumber=0;
                            d.fitGoodsSnList=d.goodsSnList;
                            d.addGoodsSnList=[];
                            d.delGoodsSnList=[];
                        } else {
                            vo.addNumber = d.addGoodsSnList.length;
                            vo.delNumber = d.delGoodsSnList.length;
                        }
                        vo.fitGoodsSnList = genUploadTableList(d.fitGoodsSnList);
                        vo.delGoodsSnList = genUploadTableList(d.delGoodsSnList);
                        vo.addGoodsSnList = genUploadTableList(d.addGoodsSnList);
                    } else {
                        if (vo.stockNum > vo.number) {
                            vo.addNumber = 0;
                            vo.delNumber = vo.stockNum - vo.number;
                        } else {
                            vo.delNumber = 0;
                            vo.addNumber = vo.number - vo.stockNum;
                        }
                    }
                    vo.remark = d.remark;
                    list.push(vo);
                });

                entity.checkHouseGoodsVoList = list;

                console.log(JSON.stringify(entity));
                tipLoad("盘点单新增中...");
                post("${baseUrl}house/checkHouse/add.action", entity, function (res) {
                    closeAll();
                    if (res.code == 1) {
                        tip(res.msg);
                        setTimeout(function () {
                            refreshMainIframe("${baseUrl}house/checkHouse.action");
                            closeSubIframe();
                        },1000);
                    } else {
                        errTip(res.msg);
                    }
                });
                return false;
            });
        });

        function renderTable(list) {
            layui.table.render({
                id:'table',
                elem: '#table',
                data:list,
                totalRow:true,
                text: {
                    none: '请选择商品' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
                },
                cols: [[
                    {field:'index', width:70,title:"序号",templet:function (d) {
                        if (d.number > d.stockNum) {
                            return '<span class="layui-badge layui-bg-green">盘盈</span>';
                        } else if (d.number < d.stockNum) {
                            return '<span class="layui-badge layui-bg-orange">盘亏</span>';
                        } else {
                            return d.LAY_INDEX;
                        }
                    }},
                    {field: 'name', minWidth: 140, title: '名称/规格',style:"font-size:12px;",templet:function (d) {
                            return genGoodsName(d.name,d.norms)
                        }},
                    {field: 'no', width: 140, title: '商品编号',style:"font-size:12px;"},
                    {field:'stockNum', width: 90, title: '账目数量',templet:function (d) {
                            return getNumber(d.stockNum);
                        }},
                    {field:'number', width: 90, title: '实际数量',templet:"#numberBar"},
                    {width: 120, title: '单位',style:"font-size:12px;", templet:function (d) {
                            return d.goodsId == null ? "" : d.goodsUnitVoList[0].unit.name;
                        }},
                    {field:'snNumberDiv',width: 180, title: '序列号',templet: function (d) {
                            if (d.sn) {
                                if (d.addGoodsSnList == undefined) {
                                    if (emptyList(d.goodsSnList)) {
                                        d.goodsSnList = [];
                                    }
                                    return '<span style="font-size: 12px;">当前当前序列号：</span><a class="snNumberDiv currentSn">'+d.goodsSnList.length+'个</a>';
                                } else {
                                    return '            吻合的序列号：<a class="snNumberDiv fitSn">'+d.fitGoodsSnList.length+'个</a><br>' +
                                        '            盘盈的序列号：<a class="snNumberDiv addSn">'+d.addGoodsSnList.length+'个</a><br>' +
                                        '            盘亏的序列号：<a class="snNumberDiv delSn">'+d.delGoodsSnList.length+'个</a>';
                                }
                            }
                            return '';
                        }},
                    {field: 'remark', width: 120, title: '备注',style:"font-size:12px;",edit:"text"},
                    {title: '操作', minWidth: 70, fixed:'right', templet: '#operBar'},
                ]],
                limit: Number.MAX_VALUE,
                done: function(res, curr, count){
                    $(".currentSn").unbind().bind('click',function () {
                        let index = $(this).parents('tr').data('index');
                        let tableData = layui.table.cache.table;
                        showSnList(tableData[index].name, tableData[index].goodsSnList);
                    });
                    $(".fitSn").unbind().bind('click',function () {
                        let index = $(this).parents('tr').data('index');
                        let tableData = layui.table.cache.table;
                        showSnList(tableData[index].name, tableData[index].fitGoodsSnList);
                    });
                    $(".addSn").unbind().bind('click',function () {
                        let index = $(this).parents('tr').data('index');
                        let tableData = layui.table.cache.table;
                        showSnList(tableData[index].name, tableData[index].addGoodsSnList);
                    });
                    $(".delSn").unbind().bind('click',function () {
                        let index = $(this).parents('tr').data('index');
                        let tableData = layui.table.cache.table;
                        showSnList(tableData[index].name, tableData[index].delGoodsSnList);
                    });

                    $(".number").unbind("blur").bind("blur",function () {
                        let $input=$(this);
                        let number = genNumber($input.val());
                        processNumber(number, $input,true,true);
                        processTotalRow();
                    });

                    $(".numberSn").unbind("click").bind("click",function () {
                        snIndex = $(this).parents('tr').data('index');
                        let goodsId = layui.table.cache.table[snIndex].goodsId;
                        console.log("houseId:${houseId}");
                        console.log("goodsId:"+goodsId);
                        let houseId = $("[name='houseId']").val();
                        if (houseId == "" ) {
                            errTip("请选择仓库");
                            return;
                        }
                        openSnCheckHouseDialog("管理序列号","${baseUrl}dialog/sn/checkHouse.action?houseId="+houseId+"&goodsId="+goodsId, function (layero, index) {
                            var iframe = window[layero.find('iframe')[0]['name']];
                            let d = layui.table.cache.table[snIndex];
                            iframe.setSnList(d.goodsSnList,d.fitGoodsSnList,d.delGoodsSnList,d.addGoodsSnList);
                        });
                    });

                    setTotalAmount();
                    processTotalRow();
                }
            });

            layui.table.on('tool(table)', function (obj) {
                if (obj.event === 'delete') {
                    operator_del(obj);
                }
            });
        }

        /**
         * 开启sn号的商品，会回调这个函数
         *
         */
        function processCheckHouseSn(addGoodsSnList,delGoodsSnList,fitGoodsSnList) {
            //修改后的sn
            layui.table.cache.table[snIndex].addGoodsSnList = addGoodsSnList;
            layui.table.cache.table[snIndex].delGoodsSnList = delGoodsSnList;
            layui.table.cache.table[snIndex].fitGoodsSnList = fitGoodsSnList;
            reloadGoodsTable();
            let total = addGoodsSnList.length + fitGoodsSnList.length;
            processNumber(total, $("tr[data-index='"+snIndex+"']").find(".number"),true,true);
            processTotalRow();
            $(window).focus();
        }


        /**
         * 如果使用商品选择窗口，必须实现此函数，否则取不到已选择的商品数据
         * @param data
         */
        function getSelectGoods(data) {
            //处理显示数据
            let existNames = '';
            $.each(data,function (i,d) {
                if (hasId(layui.table.cache.table,d.id)){
                    existNames += d.name+'、';
                } else {
                    d.goodsId = d.id;
                    d.stockNum = emptyEntity(d.stockNum) ? 0:d.stockNum;
                    layui.table.cache.table.push(d);
                }
            });
            if (existNames!='') {
                existNames = existNames.substring(0,existNames.length-1);
                errTip("商品" + existNames + "已存在");
            }
            reloadGoodsTable();
            $(window).focus();
        }

        function processTotalRow() {
            let number = 0;
            let stockNum = 0;
            $.each(layui.table.cache.table, function (i,d) {
                number += d.number;
                stockNum += d.stockNum;
            });
            setTotalRowWithCenter("number",genNumber(number));
            setTotalRowWithCenter("stockNum",genNumber(stockNum));
            setTotalRow("1","合计");
        }

        //处理数量空间
        function processNumber(number, $input) {
            $input.val(number);
            $input.html(number);

            let index = $input.parents('tr').data('index');
            let tableData = layui.table.cache.table;
            tableData[index].number = number;

            //不是整数，但是单位有不支持小数
            let goodsUnitVo = tableData[index].goodsUnitVoList[0];

            if (!isInteger(number) && ((goodsUnitVo.unit.point!=null && !goodsUnitVo.unit.point))){
                errTip("此单位不允许小数，可以在单位中设置");
                $input.val(tableData[index].stockNum);
                $input.html(tableData[index].stockNum);
                tableData[index].number = tableData[index].stockNum;
                return;
            }

            if (number > tableData[index].stockNum) {
                $input.parents('tr').find('[data-field="index"] .layui-table-cell').html('<span class="layui-badge layui-bg-green">盘盈</span>');
            } else if (number < tableData[index].stockNum){
                $input.parents('tr').find('[data-field="index"] .layui-table-cell').html('<span class="layui-badge layui-bg-orange">盘亏</span>');
            }
        }

        function genNumber(data) {
            let number;
            if (!isNumber(data)){
                number = 0;
            } else {
                number = getNumber(data);
            }
            return number;
        }
    </script>

</html:header>
<body>

<div style="width: 100%; margin-bottom: 20px;overflow: hidden;" >
    <button class="layui-btn select-goods">选择商品</button>

    <div style="float: right;">
        <button id="save" class="layui-btn">保存</button>
        <button class="layui-btn layui-btn-primary" id="cancel">取消</button>
    </div>
</div>

<div class="layuimini-container">
    <div class="layuimini-main">
        <h2 class="tableBeforeTitle">商品盘点单</h2>
        <div style="height: 4px;background-color: #bbbbbb;width: 100%;margin: 20px 0 2px 0;"></div>
        <div style="height: 1px;width: 100%;background-color: #dddddd;margin-bottom: 10px;"></div>
        <div style="height: 10px;"></div>

        <form class="layui-form" action="" lay-filter="form">
            <input type="hidden" name="close" value="false">
            <button style="display: none;" lay-submit lay-filter="save" class="layui-btn">保存</button>

            <div class="layui-form-item">
                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">编号</div>
                    <div style="display: inline-block;width: 160px;">
                        <input type="text" id="no" name="no" class="layui-input readonly" readonly style="font-size: 12px;">
                    </div>
                </div>

                <div class="layui-inline">
                    <input type="hidden" name="houseId">
                    <div class="label">盘点仓库</div>
                    <div style="display: inline-block;width: 160px;">
                        <cascader id="selectHouse"></cascader>
                    </div>
                </div>

                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">业务日期</div>
                    <div style="display: inline-block;width: 160px;">
                        <input type="text" name="date" id="date" lay-verify="date" autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-inline" style="margin-bottom: 4px;">
                    <div class="label">经手人</div>
                    <div style="display: inline-block;width: 160px;">
                        <select name="userId" lay-verify="userId" lay-filter="userId">
                        </select>
                    </div>
                </div>
            </div>

            <table class="layui-hide" id="table" lay-filter="table" lay-size="sm"></table>

            <div style='margin: -10px 0 0 0;'>
                <table class="layui-table">
                    <tbody>
                    <tr>
                        <td>
                            <div style="position: relative;">
                                <input type="text" id="remark" name="remark" class="layui-input no-border" style="padding-left: 60px;">
                                <div style="position: absolute;top: 10px;left: 10px;">
                                    备注:
                                </div>
                            </div>
                        </td>
                        <td class="save" style="background-color: #1E9FFF;color:#ffffff;text-align: center;font-size: 16px;">保存(ctrl+s)</td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </form>
    </div>

    <script type="text/html" id="operBar">
        <a class="layui-btn layui-btn-xs layui-btn-danger table-operator" lay-event="delete">删除</a>
    </script>

    <script type="text/html" id="numberBar" >
            {{# if(d.sn==true){ }}
            <span class="number">{{ getNumber(d.number) }}</span>
            <span class="numberSn">sn</span>
            {{# }else{ }}
            <div style="margin-right: -15px;margin-left: -15px;">
                <input type="number" name="number" class="layui-input number no-border" value="{{ getNumber(d.number) }}" style="background: #ffffff;height: 28px;line-height: 28px;">
            </div>
            {{# } }}
    </script>


</div>

</body>
<html:snListDialog/>
<html:loading/>

<script>
    function openSnCheckHouseDialog(title, url, process) {
        let area;
        if (document.documentElement.clientWidth>600){
            area = ['550px', '560px'];
        }else {
            area = [(document.documentElement.clientWidth-80)+'px', '560px'];
        }

        layer.open({
            title:title,
            area: area,
            skin: 'layui-layer-molv',
            type: 2,
            content: url,
            success: function(layero, index){
                if (process != undefined){
                    process(layero, index);
                }
            }
        });
    }
</script>
</html>